/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bpmlab.shift.config;

import bpmlab.shift.dao.JpaUtil;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.persistence.EntityManager;

/**
 *
 * @author Mikael Lima
 */
public class Transacao implements PhaseListener {

    private static final Logger LOG = Logger.getLogger(Transacao.class.getName());
    private EntityManager entityManager;

    @Override
    public void afterPhase(PhaseEvent pe) {
        try {
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            if (entityManager.isOpen() && entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
            }
            LOG.log(Level.INFO, "ERRO NA CAMADA DAO", e);
        } finally {
            System.out.println("CLOSE TRANSACTION");
            JpaUtil.closeEntityManager();
        }
    }

    @Override
    public void beforePhase(PhaseEvent pe) {
        entityManager = JpaUtil.getEntityManager();
        entityManager.getTransaction().begin();
        System.out.println("OPEN TRANSACTION");
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.INVOKE_APPLICATION;
    }

}
